<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Storage;

class UploadController extends Controller
{
    use AdminTrait;

    public $imgMaxSize=5242880;//5m

    public function upload_file(Request $request)
    {
        $input=$request->all();
//        过滤数据
        $validator = Validator::make($input, [
            'file' => 'bail|required',
            'store' => 'required|in:goods,online_img,document,dev,customer_avatars,icon,saas/contract,saas/voucher',
        ],['required'=>'文件不存在']);
        if($validator->fails())
        {
            return $this->error(['-1',$validator->errors()->first()]);
        }
        $fileInfo=$_FILES['file'];
        if ($fileInfo ['error'] > 0) {
            $mes = '';
            switch ($fileInfo ['error']) {
                case 1 :
                    $mes = '上传文件超过了PHP配置文件中upload_max_filesize选项的值';
                    break;
                case 2 :
                    $mes = '超过了表单MAX_FILE_SIZE限制的大小';
                    break;
                case 3 :
                    $mes = '文件部分被上传';
                    break;
                case 4 :
                    $mes = '没有选择上传文件';
                    break;
                case 6 :
                    $mes = '没有找到临时目录';
                    break;
                case 7 :
                case 8 :
                    $mes = '系统错误';
                    break;
            }
            return $this->error(['-1', $mes]);
        }
        if ($fileInfo ['size'] > $this->imgMaxSize) {
            return $this->error(['-1','文件过大']);
        }
        $store=$input['store'];
        $ossPath=empty(config('filesystems.disks.oss.directory'))?"":config('filesystems.disks.oss.directory').DIRECTORY_SEPARATOR;
        $ossPath.=($request->store?$request->store:$store)."/".date('ym/d');
        $path=$request->file('file')->store($ossPath);
        if($path)
        {
            $data=[
                'path'=>  $path,
                'src'=>  getOSSUrl($path),
            ];
            return $this->success($data);
        }
        return $this->error(['-1','上传失败']);
    }

}
